package me.khrystal.rxnews.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.fasterxml.jackson.databind.deser.Deserializers;
import com.socks.library.KLog;
import com.zhy.changeskin.SkinManager;

import me.khrystal.rxnews.BuildConfig;
import me.khrystal.rxnews.R;
import me.khrystal.rxnews.annotation.ActivityFragmentInject;
import me.khrystal.rxnews.app.AppManager;
import me.khrystal.rxnews.module.news.ui.NewsActivity;
import me.khrystal.rxnews.module.photo.ui.PhotoActivity;
import me.khrystal.rxnews.module.settings.ui.SettingsActivity;
import me.khrystal.rxnews.module.video.ui.VideoActivity;
import me.khrystal.rxnews.utils.GlideCircleTransform;
import me.khrystal.rxnews.utils.RxBus;
import me.khrystal.rxnews.utils.SlidrUtil;
import me.khrystal.rxnews.utils.SpUtil;
import me.khrystal.rxnews.utils.ViewUtil;
import me.khrystal.rxnews.utils.slidr.model.SlidrInterface;
import rx.Observable;
import rx.functions.Action1;

/**
 * @FileName: me.khrystal.rxnews.base.BaseActivity.java
 * @Fuction: Activity 基类
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-03-07 15:14
 * @UpdateUser:
 * @UpdateDate:
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity
        implements View.OnClickListener,BaseView{
    /**
     * 代理类通用行为
     */
    protected T mPresenter;

    /**
     * 标示该activity是否可滑动退出，默认false
     */
    protected boolean mEnableSlidr;

    /**
     * 布局id
     */
    protected int mContentViewId;

    /**
     * 是否存在NavigationView
     */
    protected boolean mHasNavigationView;

    /**
     * 滑动布局
     */
    protected DrawerLayout mDrawerLayout;

    /**
     * 侧滑导航布局
     */
    protected NavigationView mNavigationView;

    private Class mClass;

    /**
     * 菜单的id
     */
    private int mMenuId;

    /**
     * Toolbar标题
     */
    private int mToolbarTitle;

    /**
     * 默认选中菜单项
     */
    private int mMenuDefaultCheckedItem;

    /**
     * Toolbar左侧按钮样式
     */
    private int mToolbarIndicator;

    /**
     * 控制是否滑动的接口
     */
    protected SlidrInterface mSlidrInterface;

    /**
     * 结束Activity的被观察者
     */
    private Observable<Boolean> mFinishObservable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getClass().isAnnotationPresent(ActivityFragmentInject.class)){
            ActivityFragmentInject annotation = getClass()
                    .getAnnotation(ActivityFragmentInject.class);
            mContentViewId = annotation.contentViewId();
            mEnableSlidr = annotation.enableSlidr();
            mHasNavigationView = annotation.hasNavigationView();
            mMenuId = annotation.menuId();
            mToolbarTitle = annotation.toolbarTitle();
            mToolbarIndicator = annotation.toolbarIndicator();
            mMenuDefaultCheckedItem = annotation.menuDefaultCheckedItem();
        } else {
          throw new RuntimeException(
                  "Class must add annotations of ActivityFragmentInject.class"
          );
        }

        if (BuildConfig.DEBUG){
            //Debug时启动严苛模式 在UI线程使用读写磁盘，网络时打印错误日志
            StrictMode.setThreadPolicy(
                    new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()
            );
            //检查内存泄漏 资源未释放等
            StrictMode.setVmPolicy(
                    new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()
            );
        }
//在SettingsActivity 启用 SkinManager
        if (this instanceof SettingsActivity){
            SkinManager.getInstance().register(this);
        }

        //通过mEnableSlidr 与 mHasNavigationView 设置主题 同时需要判断是否为夜间模式

        if (!mEnableSlidr && mHasNavigationView){
            setTheme(SpUtil.readBoolean("enableNightMode") ? R.style.BaseAppThemeNight_AppTheme:
            R.style.BaseAppTheme_AppTheme);
        } else {
            setTheme(SpUtil.readBoolean("enableNightMode") ? R.style.BaseAppThemeNight_SlidrTheme:
            R.style.BaseAppTheme_SlidrTheme);
        }

        setContentView(mContentViewId);

        if (mEnableSlidr && !SpUtil.readBoolean("disableSlide")){
            //默认开启侧滑，默认是整个页码侧滑
            mSlidrInterface = SlidrUtil
                    .initSlidrDefaultConfig(this,SpUtil.readBoolean("enableSlideEdge"));
        }

        initToolbar();

        if (mHasNavigationView){
            initNavigationView();
            initFinishRxBus();
        }

        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter != null) mPresenter.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//
//        if (this instanceof SettingsActivity){
//            SkinManager.getInstance().unregister(this);
//        }
        if (mPresenter!=null){
            mPresenter.onDestory();
        }

        if (mFinishObservable != null){
            RxBus.get().unregister("finish",mFinishObservable);
        }
//防止输入法内存泄漏
        ViewUtil.fixInputMethodManagerLeak(this);
    }

    private void initToolbar(){
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        if (toolbar != null){
            //set custom toolbar as actionBar in other to set DrawableLayout;
            setSupportActionBar(toolbar);
            //support click back
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            if (mToolbarTitle!=-1)setToolbarTitle(mToolbarTitle);
            if (mToolbarIndicator!=-1){
                setToolbarIndicator(mToolbarIndicator);
            }else {
                setToolbarIndicator(R.drawable.ic_menu_back);
            }
        }
    }

    protected void setToolbarIndicator(int resId){
        if (getSupportActionBar()!=null){
            getSupportActionBar().setHomeAsUpIndicator(resId);
        }
    }

    protected void setToolbarTitle(String str){
        if (getSupportActionBar()!=null){
            getSupportActionBar().setTitle(str);
        }
    }

    protected void setToolbarTitle(int strId) {
        if (getSupportActionBar()!=null){
            getSupportActionBar().setTitle(strId);
        }
    }

    protected ActionBar getToolbar(){
        return getSupportActionBar();
    }

    protected View getDecorView(){
        return getWindow().getDecorView();
    }

    protected abstract void initView();


    private void initNavigationView() {
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
            //supprot 4.4 statusbar fitsSystemWindows
            mDrawerLayout.setFitsSystemWindows(false);
            final CoordinatorLayout coordinatorLayout = (CoordinatorLayout)findViewById(
                    R.id.coordinator_layout
            );
            if (coordinatorLayout!=null){
                coordinatorLayout.setFitsSystemWindows(true);
            }
        }

        mNavigationView = (NavigationView)findViewById(R.id.navigation_view);
        if (mMenuDefaultCheckedItem!=-1)mNavigationView.setCheckedItem(mMenuDefaultCheckedItem);
        mNavigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem item) {
                        if (item.isChecked())return true;
                        switch (item.getItemId()){
                            case R.id.action_news:
                                mClass = NewsActivity.class;
                                break;
                            case R.id.action_video:
                                mClass = VideoActivity.class;
                                break;
                            case R.id.action_photo:
                                mClass = PhotoActivity.class;
                                break;
                            case R.id.action_settings:
                                mClass = SettingsActivity.class;
                                break;
                        }
                        mDrawerLayout.closeDrawer(Gravity.LEFT);
                        return false;
                    }
                }
        );

        mNavigationView.post(new Runnable() {
            @Override
            public void run() {
                final ImageView imageView = (ImageView)BaseActivity
                        .this.findViewById(R.id.avatar);
                Glide.with(mNavigationView.getContext()).load(R.drawable.ic_header)
                        .crossFade().transform(new GlideCircleTransform(mNavigationView.getContext()))
                        .into(imageView);
            }
        });

        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                if (mClass!=null){
                    showActivityReorderToFront(BaseActivity.this,mClass,false);
                    mClass = null;
                }
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }

    private void initFinishRxBus() {
        mFinishObservable = RxBus.get().register("finish",Boolean.class);
        mFinishObservable.subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean themeChange) {
                try {
                    //修改主题了 且不是当前页面
                    if (themeChange && !AppManager.getAppManager().getCurrentNavActivity().getName()
                            .equals(BaseActivity.this.getClass().getName())){
                        finish();
                        /**
                         * finish in order to not notify recreate
                         */
                    }else if (!themeChange){
                        //if in NewsActivity ,finish all Activity exit app
                        finish();
                        KLog.e("Endless"+BaseActivity.this.getClass().getName());
                    }
                }catch (ClassNotFoundException e){
                    e.printStackTrace();
                    KLog.e("Class Not Found");
                }
            }
        });
    }

    protected void showSnackbar(String msg){
        Snackbar.make(getDecorView(),msg,Snackbar.LENGTH_SHORT).show();
    }

    protected void showSnackBar(int id){
        Snackbar.make(getDecorView(),id,Snackbar.LENGTH_SHORT).show();
    }

    public void showActivityReorderToFront(Activity aty,Class<?> cls,boolean backPress){
        AppManager.getAppManager().orderNavActivity(cls.getName(),backPress);
        KLog.e("Skip to Activity:"+cls.getName());
        Intent intent = new Intent();
        intent.setClass(aty,cls);

        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        aty.startActivity(intent);
        overridePendingTransition(0,0);
    }

    public void showActivity(Activity aty,Intent it){
        aty.startActivity(it);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(mMenuId,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerLayout!=null && item.getItemId() == android.R.id.home){
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }else if(item.getItemId() == android.R.id.home && mToolbarIndicator == -1){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                finishAfterTransition();
            }else {
                finish();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
            if (mDrawerLayout!=null && mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                return true;
            /*}else if (!(this instanceof NewsActivity) && mHasNavigationView){
//                即与NewsActivity同级的页面
                try{
                    //获取当前页面的上一个页面
                    showActivityReorderToFront(this,
                            AppManager.getAppManager().getLastNavActivity(),true);
                }catch (ClassNotFoundException e){
                    e.printStackTrace();
                    KLog.e("Class Not Found");
                }
                return true;
            }else if (this instanceof NewsActivity){
                //当参数为false时 即退出应用
                RxBus.get().post("finish",false);*/
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * extend BaseView implements common method
     */
    @Override
    public void toast(String msg) {
        showSnackbar(msg);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }
}
